package com.hhf.rrd.usage.partitioner;

import com.hhf.rrd.model.Student;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * 分区
 *
 * @author huanghaifeng15
 * @date 2022/2/10 10:08
 **/
public class PartitionerApp {
    public static void main(String[] args) throws Exception {
        // 获取运行环境上下文
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        
        // 获取流式数据源
        DataStreamSource<String> source = env.readTextFile("data/user_register.log");

        // 处理词频的业务逻辑  Transformation
        SingleOutputStreamOperator<Student> streamOperator = source.map(new MapFunction<String, Student>() {
            @Override
            public Student map(String value) throws Exception {
                Student student = new Student();
                String[] studentArr = value.split(",");
                student.setName(studentArr[0]);
                student.setAge(Integer.valueOf(studentArr[1]));
                student.setSex(Integer.valueOf(studentArr[2]));
                return student;
            }
        });
        
        streamOperator.partitionCustom(new Partitioner<String>() {
            @Override
            public int partition(String key, int numPartitions) {
                if ("dean".equals(key)){
                    return 1;
                }
                return 0;
            }
        }, new KeySelector<Student, String>() {
            @Override
            public String getKey(Student value) throws Exception {
                return value.getName();
            }
        });

        streamOperator.print();

        // 执行任务
        env.execute("PartitionerApp");
    }
}
